﻿using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;

namespace MCPServer.Demo.SSE
{
    // 标记此类为 MCP 服务器工具类型
    [McpServerToolType]
    public static class DemoTool
    {
        /// <summary>
        /// 服务器工具方法，用于获取当前服务器时间。
        /// 使用MCPLocalTool获取服务器时间
        /// </summary>
        /// <param name="format">时间格式字符串，默认值为 "yyyy-MM-dd HH:mm:ss"</param>
        /// <returns>当前服务器时间按照指定格式转换后的字符串</returns>

        ///标记的方法会被框架识别并注册为可用工具。
        [McpServerTool, Description("获取服务器时间")]
        public static string ServerTime([Description("格式")] string format = "yyyy-MM-dd HH:mm:ss")
        {
            Console.WriteLine($"[ServerTime] Called with format: {format}");
            return DateTime.Now.ToString(format);
        }

        /// <summary>
        /// 计算两个数字的和
        /// </summary>
        /// <param name="a">第一个数字</param>
        /// <param name="b">第二个数字</param>
        /// <returns>两个数字的和</returns>
        [McpServerTool, Description("计算两个数字的和")]
        public static double Add([Description("第一个数字")] double a, [Description("第二个数字")] double b)
        {
            return a + b;
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <param name="includeNumbers">是否包含数字</param>
        /// <returns>生成的随机字符串</returns>
        [McpServerTool, Description("生成随机字符串")]
        public static string GenerateRandomString(
            [Description("字符串长度")] int length = 10,
            [Description("是否包含数字")] bool includeNumbers = true)
        {
            const string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            const string numbers = "0123456789";
            var chars = includeNumbers ? letters + numbers : letters;

            var random = new Random();
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        /// <summary>
        /// 获取系统信息
        /// </summary>
        /// <returns>系统信息的JSON字符串</returns>
        [McpServerTool, Description("获取系统信息")]
        public static string GetSystemInfo()
        {
            var systemInfo = new
            {
                MachineName = Environment.MachineName,
                OSVersion = Environment.OSVersion.ToString(),
                ProcessorCount = Environment.ProcessorCount,
                WorkingSet = Environment.WorkingSet,
                CurrentDirectory = Environment.CurrentDirectory,
                DotNetVersion = Environment.Version.ToString()
            };

            return System.Text.Json.JsonSerializer.Serialize(systemInfo, new System.Text.Json.JsonSerializerOptions
            {
                WriteIndented = true
            });
        }
    }
}